package com.mcxx.modules.miniSalvation.family.service.write;

import cn.hutool.core.util.IdUtil;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.PropertiesConstant;
import com.mcxx.ansync.event.PropertiesEventHandler;
import com.mcxx.modules.miniSalvation.family.dao.read.FamilyMemberReadDao;
import com.mcxx.modules.miniSalvation.family.dao.write.BankWriteDao;
import com.mcxx.modules.miniSalvation.family.dao.write.FamilyMemberWriteDao;
import com.mcxx.modules.miniSalvation.family.dto.BankDTO;
import com.mcxx.modules.miniSalvation.family.dto.FamilyMemberDTO;
import com.mcxx.modules.miniSalvation.family.entity.*;
import com.mcxx.modules.miniSalvation.family.service.read.*;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCertReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilyMemberSalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.write.FamilySalaryWriteService;
import com.mcxx.modules.miniSalvation.special.entity.MemberSpecialSignEntity;
import com.mcxx.modules.miniSalvation.special.service.write.MemberSpecialSignWriteService;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



@Service("familyMemberWriteService")
@TaTransactional
public class FamilyMemberWriteService {
    @Resource
    private FamilyMemberWriteDao familyMemberWriteDao;
    @Resource
    private FamilyMemberReadDao familyMemberReadDao;
    @Autowired
    private FamilyMainWriteService familyMainWriteService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private PropertiesEventHandler propertiesEventHandler;
    @Autowired
    private FamilyMemberReadService familyMemberReadService;
    @Autowired
    private BankWriteService bankWriteService;
    @Autowired
    private MemberAssetsReadService memberAssetsReadService;
    @Autowired
    private MemberAssetsWriteService memberAssetsWriteService;
    @Autowired
    private FamilyMemberHistoryReadService familyMemberHistoryReadService;
    @Autowired
    private FamilyMainReadService familyMainReadService;
    @Autowired
    private BankWriteDao bankWriteDao;
    @Autowired
    private OrderCertReadService orderCertReadService;
    @Autowired
    private FamilySupportWriteService familySupportWriteService;
    @Autowired
    private FamilySalaryWriteService familySalaryWriteService;
    @Autowired
    private FamilyMemberSalaryReadService familyMemberSalaryReadService;
    @Autowired
    private FamilySupportReadService familySupportReadService;

    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private MemberSpecialSignWriteService memberSpecialSignWriteService;

    public void insertFamilyMember(FamilyMemberEntity entity, UserAccountVo accountVo) {


        FamilyMainEntity mainEntity = familyMainReadService.getById(entity.getFamilyId());
        entity.setAreaCode(mainEntity.getAreaCode());
        entity.setCreateTime(new Date());
        entity.setCreateBy(accountVo.getUserId());

        entity.setState(Constant.PeopleState.NORMAL);
        int rows = familyMemberWriteDao.insertIgnoreNull(entity);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999);
        }
        propertiesEventHandler.publishAddEvent(entity, PropertiesConstant.CATE_MEMBER_CHANGE, null);
    }


    public String addFamilyMember(FamilyMemberDTO dto,UserAccountVo accountVo) {



        FamilyMemberEntity entity = checkConstraint4SaveMember(dto);


        insertFamilyMember(entity, accountVo);

        dto.setId(entity.getId());

        editMemberSpecialSign(dto,accountVo);

        bankWriteService.editBankInfo(dto,accountVo);

        updateOrderFamilyInfo(dto, accountVo);


        dto.setId(entity.getId());
        orderWriteService.updateMemberInfo(dto,null);


        MemberAssetsEntity ass = new MemberAssetsEntity();
        ass.setFamilyId(entity.getFamilyId());
        ass.setOrderId(dto.getOrderId());
        this.updateFamilyRevenue(ass);
        return entity.getId();
    }


    public void updateFamilyMember(FamilyMemberEntity entity)  {
        familyMemberWriteDao.updateIgnoreNull(entity);
    }





    public void updateFamilyRelationForExpire(String familyId, String idcard)  {
        familyMemberWriteDao.updateFamilyRelationForExpire(familyId, idcard);
    }


    public void  updateFamilyMember(FamilyMemberDTO dto,UserAccountVo accountVo)  {
        String relation = familyMemberReadDao.getRelationByMemberId(dto.getId());

        OrderEntity orderEntity = orderReadService.getById(dto.getOrderId());
        dto.setAreaCode(orderEntity.getAreaCode());


        FamilyMemberEntity entity = checkConstraint4SaveMember(dto);
        FamilyMemberEntity memberEntity = familyMemberReadService.getById(entity.getId());
        if(memberEntity==null){

            insertFamilyMember(entity, accountVo);
        }else{

            entity.setIsSaveObject("0");
            updateFamilyMember(entity);
        }


        bankWriteService.editBankInfo(dto,accountVo);
        editMemberSpecialSign(dto,accountVo);


        updateOrderFamilyInfo(dto, accountVo);


        orderWriteService.updateMemberInfo(dto,relation);

        MemberAssetsEntity ass = new MemberAssetsEntity();
        ass.setFamilyId(entity.getFamilyId());
        ass.setOrderId(dto.getOrderId());
        this.updateFamilyRevenue(ass);
    }


    public void updateOrderFamilyInfo(FamilyMemberDTO familyMemberDTO, UserAccountVo accountVo){

        Map<String,Integer> countMap = familyMemberReadDao.countMemberNumAndSaveMemberNum(familyMemberDTO.getFamilyId());


        familyMainWriteService.updateFamilyInfo(familyMemberDTO, accountVo, countMap);

    }


    public void editMemberSpecialSign(FamilyMemberDTO familyMemberDTO, UserAccountVo accountVo){
        if(StringUtils.isEmpty(familyMemberDTO.getSpecialValues())){
            memberSpecialSignWriteService.deleteByIdcard(familyMemberDTO.getIdcard(),null);

        }else if(!familyMemberDTO.getSpecialValues().equals(familyMemberDTO.getOldSpecialValues())){

            memberSpecialSignWriteService.deleteByIdcard(familyMemberDTO.getIdcard(),null);
            MemberSpecialSignEntity memberSpecialSignEntity = new MemberSpecialSignEntity();
            String batch = IdUtil.simpleUUID();
            String[] special = familyMemberDTO.getSpecialValues().split(",");
            for(String value : special){
                memberSpecialSignEntity.setId(IdUtil.simpleUUID());
                memberSpecialSignEntity.setMemberId(familyMemberDTO.getId());
                memberSpecialSignEntity.setSpecialValue(value);
                memberSpecialSignEntity.setIdcard(familyMemberDTO.getIdcard());
                memberSpecialSignEntity.setStatus(Constant.SpecialSignType.CHECKED);
                memberSpecialSignEntity.setCreateTime(new Date());
                memberSpecialSignEntity.setBatch(batch);
                memberSpecialSignEntity.setCreateUser(accountVo.getUserId());
                memberSpecialSignEntity.setUpdateTime(new Date());
                memberSpecialSignEntity.setUpdateUser(accountVo.getUserId());
                int rst = memberSpecialSignWriteService.insertIgnoreNull(memberSpecialSignEntity);
                if(rst <= 0){
                    throw new BizException("-1", "成员特殊标识信息失败");
                }
            }
        }


    }


    public void delete(FamilyMemberEntity entity) {
        int rows = familyMemberWriteDao.delete(entity);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999);
        }
    }

    public void deleteFamilyMemberByIdcard(String idcard) {
        familyMemberWriteDao.deleteFamilyMemberByIdcard(idcard);

    }


    public void delete(FamilyMemberDTO dto,UserAccountVo accountVo) {

        FamilyMemberEntity entity = familyMemberReadDao.getById(dto.getId());
        if (Constant.DomesticRelation.ONESELF.equals(entity.getFamilyRelation())) {

            throw new BizException(FailureCode.ERR_9999.getCode(),"'户主不可以删除'");
        }
        if(Constant.IsApply.YES.equals(entity.getIsApply())){

            throw new BizException(FailureCode.ERR_9999.getCode(),"申请人不可以删除");
        }


        this.verifyDelMember(dto.getFamilyId(), dto.getId(), dto.getOrderId());


        this.delete(entity);


        updateOrderFamilyInfo(dto, accountVo);


        MemberAssetsEntity ass = new MemberAssetsEntity();
        ass.setFamilyId(dto.getFamilyId());
        ass.setOrderId(dto.getOrderId());
        this.updateFamilyRevenue(ass);

        propertiesEventHandler.publishDeleteEvent(entity, PropertiesConstant.CATE_MEMBER_DEL, null);
    }

    public void verifyDelMember(String familyId, String memberId, String orderId){



        MemberAssetsEntity memberAssetsEntity = new MemberAssetsEntity();
        memberAssetsEntity.setOrderId(orderId);
        memberAssetsEntity.setFamilyId(familyId);
        memberAssetsEntity.setMemberId(memberId);
        int i = memberAssetsReadService.cntMemberAssets(memberAssetsEntity);
        if(i > 0){

            int i1 = memberAssetsWriteService.deleteByMemberId(memberId);
            if(i1 <= 0){
                throw new BizException(FailureCode.ERR_9999);
            }
        }


        int familyNums = familyMemberReadDao.getMemberNumberByFmyId(familyId);
        if(familyNums <= 1){
            throw new BizException(FailureCode.ERR_20083);
        }
    }

    public void verifyCancelMember(String familyId, String memberId, String orderId){



        MemberAssetsEntity memberAssetsEntity = new MemberAssetsEntity();
        memberAssetsEntity.setOrderId(orderId);
        memberAssetsEntity.setFamilyId(familyId);
        memberAssetsEntity.setMemberId(memberId);
        int i = memberAssetsReadService.cntMemberAssets(memberAssetsEntity);
        if(i > 0){

            int i1 = memberAssetsWriteService.deleteByMemberId(memberId);
            if(i1 <= 0){
                throw new BizException(FailureCode.ERR_9999);
            }
        }
    }


    public void changeFamilyRelation(String familyId, String orderId, Map<String,String> relationshipMap) {

        FamilyMemberEntity master = checkConstraint4ChangeMaster(relationshipMap);


        FamilyMainEntity familyMainEntity = new FamilyMainEntity();
        familyMainEntity.setId(familyId);
        familyMainEntity.setName(master.getName());
        familyMainEntity.setIdcard(master.getIdcard());
        int familyRes = familyMainWriteService.updateFamily(familyMainEntity);
        if(familyRes <= 0){
            throw new BizException(FailureCode.ERR_11300);
        }


        for (Map.Entry<String,String> entry: relationshipMap.entrySet()) {
            FamilyMemberEntity entity = new FamilyMemberEntity();
            entity.setId(entry.getKey());
            entity.setFamilyRelation(entry.getValue());
            familyMemberWriteDao.updateIgnoreNull(entity);
        }


        BankDTO bankDTO = new BankDTO();
        bankDTO.setMemberId(master.getId());
        bankDTO.setOrgId(orderId);
        bankWriteService.updateByOrderId(bankDTO);


        OrderEntity order = new OrderEntity();
        order.setOrderId(orderId);
        order.setName(master.getName());
        order.setMemberId(master.getId());
        order.setIdcard(master.getIdcard());
        orderWriteService.updateIgnoreNull(order);

    }


    public void writeOffFamilyMember(FamilyMemberDTO dto, UserAccountVo accountVo) {
        FamilyMemberEntity entity = familyMemberReadDao.getById(dto.getId());
        entity.setState(dto.getState());


        int memberCount = familyMemberReadDao.getMemberNumberByFmyId(entity.getFamilyId());


        if(entity.getFamilyRelation().equals(Constant.DomesticRelation.ONESELF) && memberCount>1){
            throw new BizException(FailureCode.ERR_10001.getCode(),"请先更换户主再进行注销操作");
        }

        if(entity.getIsApply().equals(Constant.IsApply.YES) && memberCount>1){
            throw new BizException(FailureCode.ERR_10001.getCode(),"请先更换申请人再进行注销操作");
        }

        if(Constant.IsSaveObject.YES.equals(entity.getIsSaveObject())){
            entity.setIsSaveObject(Constant.IsSaveObject.NO);
            orderWriteService.changeSaveMember("down", dto.getOrderId());
        }

        if(Constant.PeopleState.DEAD.equals(dto.getState())){
            entity.setDeadTime(dto.getDeadTime());


        }


        if(Constant.PeopleState.MARRIED.equals(dto.getState())){

            if(memberCount==1){
                throw new BizException("-1", "当前在保家庭只有一名家庭成员，不能操作嫁娶，请选择停保操作。");
            }else{






                int rst = familySupportReadService.cntInSupport(entity.getFamilyId(), entity.getIdcard());
                if(rst == 0){

                    FamilySupportEntity familySupportEntity = new FamilySupportEntity();
                    familySupportEntity.setFamilyId(entity.getFamilyId());
                    familySupportEntity.setIdcard(entity.getIdcard());
                    familySupportEntity.setName(entity.getName());
                    familySupportEntity.setSex(entity.getSex());
                    familySupportWriteService.addRecheckFamilySupport(familySupportEntity,dto.getOrderId(),dto.getId());
                }
            }
        }


        if(Constant.PeopleState.SUSPEND_STATE.equals(dto.getState())){
            if(memberCount==1){
                throw new BizException("-1", "当前在保家庭只有一名状态正常家庭成员，请在暂停管理中进行暂停管理");
            }
        }

        if(Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(dto.getState())){
            if(memberCount==1){
                throw new BizException("-1", "当前在保家庭只有一名状态正常家庭成员，不能操作分户迁出，请选择停保操作。");
            }
        }



        updateFamilyMember(entity);
        if(!"07,08".contains(dto.getState())){

            this.verifyCancelMember(dto.getFamilyId(), dto.getId(), dto.getOrderId());
        }


        dto.setFamilyRelation(entity.getFamilyRelation());

        updateOrderFamilyInfo(dto, accountVo);
        if(memberCount>1){

            MemberAssetsEntity ass = new MemberAssetsEntity();
            ass.setFamilyId(dto.getFamilyId());
            ass.setOrderId(dto.getOrderId());
            this.updateFamilyRevenue(ass);
        }

        if(entity.getFamilyRelation().equals(Constant.DomesticRelation.ONESELF)){

            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setOrderId(dto.getOrderId());
            orderEntity.setSaveMemberNumber(0);
            orderEntity.setBaseSalary(0d);
            orderEntity.setSalvMoney(0d);
            orderWriteService.updateIgnoreNull(orderEntity);

            familySalaryWriteService.deleteFamilySalaryByOrderId(dto.getOrderId());
        }
    }


    public void verifyOrderCaregiver(FamilyMemberDTO dto){
//        if(StringUtils.isNotEmpty(caregiverDto.getOrderCertIds())){





        int  rst = orderCertReadService.cntCertNum(dto.getId(),dto.getOrderId(),"911","2");

        if(rst <= 0){
            throw new BizException("-1", "当前死亡人员没有上传【死亡证明材料】，请上传！");
        }
    }


    public void restoreFamilyMember(FamilyMemberDTO dto, UserAccountVo accountVo) {

        FamilyMemberEntity entity = new FamilyMemberEntity();
        BeanUtils.copyProperties(dto,entity);


        entity.setState(Constant.PeopleState.NORMAL);


        updateFamilyMember(entity);


        FamilyMemberEntity memberEntity = familyMemberReadDao.getById(dto.getId());
        dto.setFamilyRelation(entity.getFamilyRelation());
        dto.setState(Constant.PeopleState.NORMAL);
        dto.setIsSaveObject(memberEntity.getIsSaveObject());
        updateOrderFamilyInfo(dto, accountVo);

        MemberAssetsEntity ass = new MemberAssetsEntity();
        ass.setFamilyId(dto.getFamilyId());
        ass.setOrderId(dto.getOrderId());
        this.updateFamilyRevenue(ass);


        familySupportWriteService.delFamilySupportByIdcard(dto.getIdcard(),dto.getFamilyId());
    }


    private FamilyMemberEntity checkConstraint4SaveMember(FamilyMemberDTO dto) {

        if(Constant.DomesticRelation.ONESELF.equals(dto.getFamilyRelation())){
            String masterIdCard = familyMemberReadDao.getMasterIdCardByFamilyId(dto.getFamilyId());
            if(StringUtils.isNotEmpty(masterIdCard) && !masterIdCard.equals(dto.getIdcard())){
                throw new BizException(FailureCode.ERR_20004);
            }
        }

        if(dto.getFamilyRelation().equals(Constant.DomesticRelation.SPOUSE)){

            String spouseIdCard = familyMemberReadDao.getSpouseIdCardByFamilyId(dto.getFamilyId());
            if(StringUtils.isNotEmpty(spouseIdCard) && !spouseIdCard.equals(dto.getIdcard())){
                throw new BizException(FailureCode.ERR_20030);
            }
        }

        FamilyMemberEntity entity = new FamilyMemberEntity();
        BeanUtils.copyProperties(dto,entity);
        if(StringUtils.isBlank(entity.getId())){
            entity.setId(IdUtil.simpleUUID());
        }
        return entity;
    }


    private FamilyMemberEntity checkConstraint4ChangeMaster(Map<String,String> relationshipMap) {
        Map<String,Integer> countMap = new HashMap<>();
        String masterId = null;


        for (Map.Entry<String,String> entry: relationshipMap.entrySet()) {
            countMap.put(entry.getValue(),countMap.get(entry.getValue()) == null ? 1 : countMap.get(entry.getValue()) + 1);
            if (Constant.DomesticRelation.ONESELF.equals(entry.getValue())) {
                masterId = entry.getKey();
            }
        }


        if (CommonUtil.invalidArgs(masterId)) {

            throw new BizException(FailureCode.ERR_10016);
        }
        if (countMap.get(Constant.DomesticRelation.ONESELF) > 1) {

            throw new BizException(FailureCode.ERR_20004);
        }
        if (!CommonUtil.invalidArgs(countMap.get(Constant.DomesticRelation.SPOUSE))
                && countMap.get(Constant.DomesticRelation.SPOUSE) > 1) {

            throw new BizException(FailureCode.ERR_20030);
        }
        FamilyMemberEntity master = familyMemberReadDao.getById(masterId);
        if (!Constant.PeopleState.NORMAL.equals(master.getState())) {

            throw new BizException(FailureCode.ERR_10017);
        }
        if(Constant.IsSaveObject.NO.equals(master.getIsSaveObject())){

            throw new BizException(FailureCode.ERR_10019);
        }

        return master;
    }


    public void batchUpdateStateByFamilyIds(String state, List<String> familyIdList) {
        int rows = familyMemberWriteDao.batchUpdateStateByFamilyIds(state, familyIdList);
    }


    public void changeFamilyId(String familyId, String idcard, String newFamilyId) {
        familyMemberWriteDao.updateFamilyIdByOldFamilyIdAndIdcard(familyId, idcard, newFamilyId);
    }


    public void updateByIdCard(FamilyMemberEntity memberEntity) {
        familyMemberWriteDao.updateByIdCard(memberEntity);
    }


    public void updateFirstStartDate(String type,String orderId,String businessType, String familyId, String rescueYears){

        List<FamilyMemberEntity> familyMemberEntityList = familyMemberReadService.getFirstStartDate(familyId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date rescueDate = null;
        try {
            rescueDate = sdf.parse(rescueYears + "-01");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(rescueDate);
        rightNow.add(Calendar.MONTH, -1);
        Date dt1 = rightNow.getTime();
        String reStr = sdf.format(dt1);



        for(FamilyMemberEntity entity : familyMemberEntityList){





            if (Constant.OrderType.NEW.equals(type)){

                entity.setFristStartDate(rescueYears);
                familyMemberWriteDao.updateIgnoreNull(entity);
            } else{


                String endDate = familyMemberSalaryReadService.getMemberSalaryMaxDate(orderId,entity.getId(),businessType);
                if(StringUtils.isEmpty(endDate)){
                    entity.setFristStartDate(rescueYears);
                }else{
                    if(endDate.compareTo(reStr) < 0){
                        entity.setFristStartDate(rescueYears);
                    }
                }
                if(CommonUtil.invalidArgs(entity.getFristStartDate())){
                    entity.setFristStartDate(rescueYears);
                }
                familyMemberWriteDao.updateIgnoreNull(entity);
            }

        }
    }


    public int batchUpdateIgnoreNull(List<FamilyMemberEntity> familyMember){
        return familyMemberWriteDao.batchUpdateIgnoreNull(familyMember);
    }


    public double updateFamilyRevenue(MemberAssetsEntity entity){



        Map<String, BigDecimal> familyIncomeMap = memberAssetsReadService.sumMemberAssets(entity.getFamilyId(), entity.getOrderId());


//        int familyNums = familyMemberReadDao.getMemberNumberByFmyId(entity.getFamilyId());

        int familyNums = familyMemberReadDao.getMemberNumByFmyId(entity.getFamilyId());


        BigDecimal income  = familyIncomeMap.get("income"), expenditure  = familyIncomeMap.get("expenditure");
        double familyRevenue;
        if(familyNums == 0){
            familyRevenue = 0d;
        } else {
            familyRevenue = income.subtract(expenditure)
                    .divide(new BigDecimal(familyNums), 2, BigDecimal.ROUND_HALF_UP)
                    .divide(new BigDecimal(12), 2, BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
        }


        FamilyMainEntity familyMainEntity = new FamilyMainEntity();
        familyMainEntity.setId(entity.getFamilyId());
        familyMainEntity.setFamilyRevenue(familyRevenue);
        int rst = familyMainWriteService.updateFamily(familyMainEntity);
        if(rst <= 0){
            throw new BizException(FailureCode.ERR_9999);
        }
        return familyRevenue;
    }

    public int  updateDocHelpPoor(String memberId,String docHelpPoor){
        return familyMemberWriteDao.updateDocHelpPoor(memberId,docHelpPoor);
    }


    public void changeMemberApply(String familyId, String orderId, Map<String,String> relationshipMap) {
        String applyMemberId = "";
        int count = 0;

        for(Map.Entry<String,String> entry:relationshipMap.entrySet()){
            if("1".equals(entry.getValue())){
                applyMemberId = entry.getKey();
                count++;
            }
        }
        if(count==0){
            throw new BizException(FailureCode.ERR_10051);
        }
        if(count>1){
            throw  new BizException(FailureCode.ERR_10052);
        }

        familyMemberWriteDao.changApplyMember(applyMemberId,familyId);

        FamilyMemberEntity master = familyMemberReadDao.getById(applyMemberId);

        OrderEntity order = new OrderEntity();
        order.setOrderId(orderId);
        order.setApplyName(master.getName());
        order.setApplyIdcard(master.getIdcard());
        orderWriteService.updateIgnoreNull(order);
    }


    public int changApplyMember(String familyId,String memberId){
        return  familyMemberWriteDao.changApplyMember(memberId,familyId);
    }


    public int updateNoSave(String familyId){
        return  familyMemberWriteDao.updateNoSave(familyId);
    }


    public int chengeMemberSaveObject(String orderId,String familyId,String memberId,String type,String isMaster){
        FamilyMemberEntity member = new FamilyMemberEntity();
        member.setId(memberId);
        member.setIsSaveObject(type);
        this.updateFamilyMember(member);

        FamilyMainEntity family = new FamilyMainEntity();
        family.setId(familyId);

        if("0".equals(type)){
            if("01".equals(isMaster)){
                family.setMasterInSave("02");
            }
            family.setSaveType("down");
        }else{
            if("01".equals(isMaster)){
                family.setMasterInSave("01");
            }
            family.setSaveType("up");
        }
        int i = familyMainWriteService.changeSaveMemberById(family);
        if(i <= 0){
            throw new BizException("-1", "修改家庭保障对象异常");
        }
        i = orderWriteService.changeSaveMember(family.getSaveType(), orderId);
        if(i <= 0){
            throw new BizException("-1", "修改业务保障对象异常");
        }
        return i;
    }


    public int updateIsSaveObject(String memberId, String isSaveObject){ return familyMemberWriteDao.updateIsSaveObject(memberId,isSaveObject); }


    public int updateMemberByMainHistory(String familyId, String orderId){
        return familyMemberWriteDao.updateMemberByMemberHistory(familyId, orderId);
    }


    public void recheckUpdateMember(String oldOrderId, String familyId, UserAccountVo userAccountVo){
        List<FamilyMemberDTO> familyMemberDTOList = familyMemberHistoryReadService.listByOrderId(oldOrderId);

        List<String> memberIdList = familyMemberReadDao.getMemberIdsByFamilyId(familyId);

        List<String> updateMemberId = new ArrayList<>();
        List<FamilyMemberEntity> addFamilyMemberList = new ArrayList<>();

        for(FamilyMemberDTO dto : familyMemberDTOList){
            if(memberIdList.contains(dto.getMemberId())){
                updateMemberId.add(dto.getMemberId());
            }else{
                FamilyMemberEntity entity = new FamilyMemberEntity();

                BeanUtils.copyProperties(dto, entity);

                entity.setId(dto.getMemberId());
                entity.setAreaCode(userAccountVo.getAreaCode());
                entity.setCreateTime(new Date());
                entity.setCreateBy(userAccountVo.getUserId());

                entity.setState(Constant.PeopleState.NORMAL);
                entity.setIsSaveObject(Constant.IsSaveObject.NO);
                addFamilyMemberList.add(entity);
            }
        }
        if(memberIdList.size() > 0){
            this.updateNoSave(familyId);
        }
        if(addFamilyMemberList.size() > 0){
            int rows = familyMemberWriteDao.inserts(addFamilyMemberList);
            if (rows < 1) {
                throw new BizException(FailureCode.ERR_9999);
            }
        }
    }


    public int updateExpireByFamilyId(String familyId){
        return familyMemberWriteDao.updateExpireByFamilyId(familyId);
    }


    public int resetMemberState(String familyId){
        int count = familyMemberReadDao.selectHouseholdSuspendByFamilyId(familyId);
        if(count>0){

            int i = familyMemberWriteDao.resetMemberState(familyId);

            familyMemberWriteDao.deleteUnNormalMember(familyId);
            return i ;
        }
        return 0;
    }


    public void copyFamilyMemberSource(String familyId) {
        familyMemberWriteDao.copyFamilyMemberSource(familyId);
    }

    public void copyMemberByMemberId(String memberId) {
        familyMemberWriteDao.copyMemberByMemberId(memberId);
    }


    public void deleteFamilyMemberById(String familyId) {
        familyMemberWriteDao.deleteFamilyMemberById(familyId);
    }
}
